package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description:test
 * @Create by: CAt
 * @Date;2021/9/2318:50
 */
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER =new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest servletRequest1=(HttpServletRequest) servletRequest;
        HttpServletResponse servletResponse1=(HttpServletResponse) servletResponse;
        String requestURI = servletRequest1.getRequestURI();
        String [] arr=new String[]{
                "/employee/login",
                "/employee/logout",

                "/backend/**",
                "/front/**"
        };
        //判断是不是String{}arr中的
        //如果是就放行
        for (String s : arr) {
            boolean match = PATH_MATCHER.match(s, requestURI);
            if (match){
                filterChain.doFilter(servletRequest1,servletResponse1);
                return;
            }
        }
        //判断是否登录
        //session是否有值
        if (servletRequest1.getSession().getAttribute("emloyee")!=null){
            Long emloyee = (Long) servletRequest1.getSession().getAttribute("emloyee");
            BaseContext.settt(emloyee);
            filterChain.doFilter(servletRequest1,servletResponse1);
            return;
        }
        servletResponse1.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }
}
